package com.ujiuye.servlet;

import com.ujiuye.bean.ProductBean;
import com.ujiuye.dao.ProductDao;
import com.ujiuye.service.ProductService;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/product")
public class ProductServlet extends BaseServlet {
    //创建service
    private ProductService ps = new ProductService();

    public void Productshow(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取Product集合
        List<ProductBean> pd = ps.setProduct();
        //存域
        req.setAttribute("pd", pd);
        //转发
        req.getRequestDispatcher("productshow.jsp").forward(req, resp);
    }

    public void findProductByid(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        //获取查询条件pid
        String pid = req.getParameter("pid");
        //调用service层查询pid方法
        ProductBean product = ps.findProductByid(Integer.parseInt(pid));
        //获取session
        HttpSession session = req.getSession();
        System.out.println(session);
        //设置session有效期
        session.setMaxInactiveInterval(24 * 60 * 60);
        //创建cookie保存sessionid
        Cookie ck = new Cookie("JSESSIONID", session.getId());
        System.out.println(session.getId());
        //设置cookie有效期
        ck.setMaxAge(24 * 60 * 60);
        //响应cookie
        resp.addCookie(ck);
        //从session中获取购买的商品列表
        List<ProductBean> pd = (List<ProductBean>) session.getAttribute("pd");
        //判断购物车中是否有商品，如果没有，需要创建一个集合保存商品信息
        if (pd==null) {
            pd = new ArrayList<>();
        }
            //将购买的商品加入集合中
            pd.add(product);
            //重新保存回session域中
            session.setAttribute("pd",pd );
            //跳转到购物页面
            resp.sendRedirect("trolley.jsp");

    }
}
